import { request, setToken } from '../../services/request';
import { setBaseUrl, getBaseUrl } from '../../services/request';

// 登录接口
export const loginApi = async (username: string, password: string) => {
    const res = await request('/app/auth/login', {
        method: 'POST',
        body: JSON.stringify({ num: username, password }),
    });
    // console.log('登录接口返回:', res);
    return res;
};

// 保存Token
export const saveToken = async (token: string) => {
    await setToken(token);
};

// 获取当前服务器地址
export const getCurrentBaseUrl = async () => {
    try {
        const currentUrl = await getBaseUrl();
        // 移除末尾的 /api/ 以便用户编辑
        const displayUrl = currentUrl.replace(/\/api\/$/, '');
        return displayUrl;
    } catch (error) {
        console.log('获取当前服务器地址失败:', error);
        throw error;
    }
};

// 设置服务器地址
export const updateBaseUrl = async (url: string) => {
    if (!url.trim()) {
        throw new Error('请输入服务器地址');
    }
    await setBaseUrl(url.trim());
}; 